package namespace

import (
	"gitee.com/bigmouth/quick-mock/src/domain/entity"
	"gitee.com/bigmouth/quick-mock/src/domain/service"
	"gitee.com/bigmouth/quick-mock/src/infrastructure/server"
)

type AddApiReq struct {
	Namespace    string           `json:"namespace" binding:"required"`
	ResponseData string           `json:"response_data"`
	Delay        int64            `json:"delay"`
	MatchRules   []MatchRuleParam `json:"match_rules"`
}

type MatchRuleParam struct {
	MatchType string `json:"match_type" binding:"required"`
	DataPath  string `json:"data_path" binding:"required"`
	Pattern   string `json:"pattern" binding:"required"`
}

func addApi(c *server.Context) (server.JsonObject, error) {
	reqParam := AddApiReq{}
	if err := c.BindJSON(&reqParam); err != nil {
		return nil, err
	}
	matchRules := make([]entity.MatchRule, 0)
	for _, rule := range reqParam.MatchRules {
		matchRule, err := entity.NewMatchRule(rule.MatchType, rule.DataPath, rule.Pattern)
		if err != nil {
			return nil, err
		}
		matchRules = append(matchRules, matchRule)
	}

	err := service.GetNamespaceInstance().AddMockApi(
		reqParam.Namespace,
		reqParam.ResponseData,
		reqParam.Delay,
		matchRules,
	)
	if err != nil {
		return nil, err
	}
	return nil, nil
}
